<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    @load="onLoad"
    :error.sync="error"
    error-text="请求失败，点击重新加载"
  >
    <comment-item
      v-for="(item, index) in list"
      :key="index"
      :comment="item"
      @reply-click="$emit('reply-click', $event)"
    />
  </van-list>
</template>

<script>
import { getComments } from '@/api/comment'
import CommentItem from './comment-item.vue'

export default {
  name: 'CommentList',
  components: { CommentItem },
  props: {
    source: {
      type: String,
      required: true,
    },
    list: {
      type: Array,
      default: () => [],
    },
    type: {
      type: String,
      default: 'a',
      validator(val) {
        return ['a', 'c'].includes(val)
      },
    },
  },
  data() {
    return {
      loading: false,
      finished: false,
      offset: null, //加载下一页列表的页码值
      limit: 5, //每页评论的数量
      error: false, //错误提示
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    async onLoad() {
      //请求获取数据
      try {
        const { data } = await getComments({
          type: this.type,
          source: this.source,
          offset: this.offset,
          limit: this.limit,
        })
        // if (Math.random() > 0.5) {
        //   JSON.parse('akjshfddksjahf')
        // }
        //将数据添加到list数组中
        const { results } = data.data
        this.list.push(...results)
        //将loading设置为false
        this.loading = false
        //判断是否还有数据
        if (results.length) {
          //有数据,更新下一页
          this.offset = data.data.last_id
        } else {
          this.finished = true
        }
      } catch (err) {
        console.log(err)
        this.error = true
        this.loading = false
      }
    },
  },
}
</script>

<style lang="less" scoped></style>
